<template>
  <div>
    <el-row v-if="showList">
      <el-col :span="5" style="padding-left: 20px; padding-top: 20px; border-right: 1px solid #dfe6ec">
        <customTree :ancestralId="treeQuery.ancestralId" :btnTitle="'  添加数据抽取任务目录  '" @getId="getId" :type="true" @getTree="getTree" :expandType="'1'" />
      </el-col>
      <el-col :span="19">
        <div class="app-container jobPage">
          <div class="filter-container">
            <div class="filter-item">
              <span class="span">数据抽取名称 </span>
              <el-input v-model="listQuery.jobName" placeholder="请输入数据抽取名称" style="width: 200px" />
            </div>
            <!--          <div class="filter-item">-->
            <!--            <span class="span">调度类型 </span>-->
            <!--            <el-select v-model="listQuery.dbType" clearable placeholder="调度类型" style="width: 200px">-->
            <!--              <el-option-->
            <!--                v-for="item in dictList('datasource_type')"-->
            <!--                :key="'type' + item.label"-->
            <!--                :label="item.label"-->
            <!--                :value="item.value" />-->
            <!--            </el-select>-->
            <!--          </div>-->
            <div class="filter-item">
              <span class="span">任务状态 </span>
              <el-select v-model="listQuery.checkStatus" clearable placeholder="请选择任务状态" style="width: 200px">
                <el-option v-for="item in dictList('job_check_status')" :key="'type' + item.label" :label="item.label" :value="item.value" />
              </el-select>
            </div>
            <!--          <div class="filter-item">-->
            <!--            <span class="span">执行状态 </span>-->
            <!--            <el-select v-model="listQuery.isSync" clearable placeholder="请选择执行状态" style="width: 100px">-->
            <!--              <el-option-->
            <!--                v-for="item in dictList('is_sync')"-->
            <!--                :key="'type' + item.label"-->
            <!--                :label="item.label"-->
            <!--                :value="item.value" />-->
            <!--            </el-select>-->
            <!--          </div>-->
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
              {{ $t('table.search') }}
            </el-button>
            <el-button v-waves plain v-permission="['metadata:source:add']" class="filter-item" styel="margin-left: 10px" type="primary" icon="el-icon-plus" @click="handleSingle">
              新建接入任务
            </el-button>

            <el-button v-waves class="filter-item" icon="el-icon-refresh" @click="handleRest">{{ $t('table.rest') }}</el-button>

            <!--          <el-button v-waves v-permission="['metadata:source:delete']" class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleBathDelete">-->
            <!--            {{ $t('table.delete') }}-->
            <!--          </el-button>-->
            <!--          <el-button v-waves v-permission="['metadata:source:import']" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleImport">-->
            <!--            {{ $t('table.import') }}-->
            <!--          </el-button>-->
            <!--          <el-button v-waves v-permission="['metadata:source:export']" :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">-->
            <!--            {{ $t('table.export') }}-->
            <!--          </el-button>-->
          </div>

          <el-table ref="table" :key="tableKey" v-loading="listLoading" element-loading-text="正在加载，请稍后" :data="list" border fit highlight-current-row @row-dblclick="handleRowDoubleClick">
            <!--          @selection-change="handleSelectionChange"-->

            <!--          <el-table-column type="selection" width="55" />-->
            <!--          <el-table-column type="index" align="center" width="100" label="序号" />-->
            <el-table-column label="数据抽取名称" align="center" min-width="150px" fixed="left">
              <template slot-scope="{ row }">
                <span>{{ row.jobName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="来源数据源名称" align="center" min-width="150px">
              <template slot-scope="{ row }">
                <span>{{ row.sourceDatasourceName }}</span>
              </template>
            </el-table-column>

            <el-table-column label="任务描述" align="center" min-width="150px">
              <template slot-scope="{ row }">
                <span>{{ row.description }}</span>
              </template>
            </el-table-column>

            <el-table-column label="执行状态" align="center" min-width="120px">
              <template slot-scope="{ row }">
                <span>{{ row.executeStatus | dictLabel('job_execute_state') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="任务状态" align="center" min-width="120px">
              <template slot-scope="{ row }">
                <span>{{ row.checkStatus | dictLabel('job_check_status') }}</span>
              </template>
            </el-table-column>

            <!--          <el-table-column label="数据抽取类型" align="center" min-width="150px">-->
            <!--            <template slot-scope="{row}">-->
            <!--              <span>{{ row.jobConfig | dictLabel('extraction_type') }}</span>-->
            <!--            </template>-->
            <!--          </el-table-column>-->
            <el-table-column label="创建时间" align="center" min-width="180px">
              <template slot-scope="{ row }">
                <span>{{ row.createDate }}</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" align="center" min-width="200" class-name="small-padding fixed-width">
              <template slot-scope="{ row }">
                <!--              <el-button v-if="row.checkStatus==0"  type="text" size="small" icon="el-icon-video-play" style="margin-left: 10px;" @click="handleChangeJobStatus(row, '1', '启动')">开始</el-button>-->
                <!--              <el-button v-if="row.checkStatus==1"  type="text" size="small" icon="el-icon-video-pause" class="delete-text-btn" style="margin-left: 10px;" @click="handleChangeJobStatus(row, '0', '停止')">停止</el-button>-->
                <el-button size="small" type="text" icon="el-icon-video-play" @click="runJobNow(row)">执行一次</el-button>
                <el-button v-permission="['dataextraction:DataExtraction:update']" type="text" size="small" icon="el-icon-edit" @click="handleRoweditClick(row)">
                  {{ $t('table.edit') }}
                </el-button>
                <el-button v-permission="['dataextraction:DataExtraction:delete']" type="text" size="small" icon="el-icon-delete" class="delete-text-btn" @click="handleDelete(row)">
                  {{ $t('table.delete') }}
                </el-button>
                <!-- <el-button size="small" type="text" @click="handleRowDoubleClick(row)"> 详情 </el-button> -->
                <!-- <el-button v-permission="['dataextraction:DataExtraction:update']" type="text" size="small" icon="el-icon-close" v-if="row.checkStatus === '1'" class="delete-text-btn" @click="handleStopOrOpen(row, 'stop')">禁用
                </el-button> -->
              </template>
            </el-table-column>
            <el-table-column label="是否启用" align="center" min-width="100" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="{ row }">
                <el-button v-permission="['dataextraction:DataExtraction:update']" type="text" size="small" icon="el-icon-turn-off" v-if="row.checkStatus != '1'" @click="handleStopOrOpen(row, 'open')"
                  >否
                </el-button>
                <el-button v-permission="['dataextraction:DataExtraction:update']" type="text" size="small" icon="el-icon-open" v-if="row.checkStatus === '1'" @click="handleStopOrOpen(row, 'stop')"
                  >是
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <multitasking ref="multitasking" @refreshList="refreshList"></multitasking>
          <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" :page-sizes="pageArray" @pagination="getList" />
          <single ref="single" v-if="openSingle" :visible.sync="openSingle" @refreshList="refreshList" :propValue="dataToSend" :porpObj="editdata" @done="handleDoneSingle"></single>
        </div>
      </el-col>

      <lodingFile v-if="lodingIsbool" :details="details" @change="statusisboolFun" />
    </el-row>
    <el-dialog title="提示" :visible.sync="dialogVisibleopen" width="30%" :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="150px">
        <el-form-item label="数据抽取姓名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="来源数据源名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleopen = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleopen = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { deletesource, fetchsourceList, exportsource, syncsource } from '@/api/metadata/source/source'
import { getDataextractionJobList, delDataextractionJob, stopDataextractionJob, getDataextractionJobDetail } from '@/api/dataextractionrealtime/single.js'
import { fetchMasterdataDirectoryList, createMasterdataDirectory, updateMasterdataDirectory, getMasterdataDirectory, deleteMasterdataDirectory } from '@/api/masterdata/masterdataDirectory'
import Import from '@/components/Import/import'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import sourceForm from './sourceForm'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
import multitasking from './dataextractionJobChild/multitasking.vue'
import single from './dataextractionJobSingle/multitasking'
import { changeJobStatus, startOneForSpark } from '@/api/dataextractiontask/dataExtractionTask'
import { startOne } from '@/api/datagovernancetask/dataGovernanceTask'

import customTree from '@/components/customTree/index.vue'
import lodingFile from './lodingFile.vue'
export default {
  name: 'sourceList',
  components: {
    sourceForm,
    Pagination,
    Import,
    multitasking,
    single,
    lodingFile,
    customTree,
  },
  directives: { waves, permission },
  data() {
    return {
      size: '',
      lodingIsbool: false,
      dialogVisibleopen: false,
      openSingle: false,
      showList: true,
      tableKey: 0,
      list: null,
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        type: '1',
        jobName: undefined,
        dbType: undefined,
        executeStatus: undefined,
        checkStatus: undefined,
        isSync: undefined,
        directoryId: '',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
      treeQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '7',
      },
      treeList: [],
      NODE_KEY: 'id', // id对应字段
      MAX_LEVEL: 5, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      initParam: {
        // 新增参数
        name: '新增节点',
        parentId: 0,
        children: [],
      },
      currentNodekey: '',
      dialogStatus: '',
      form: {},
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },

  methods: {
    refreshList() {
      this.listQuery.ancestralId = '7'
      this.getList()
    },
    getId(data) {
      this.listQuery.ancestralId = '7'

      this.listQuery.directoryId = data.id
      this.getList()
    },
    getTree(data) {
      this.treeList = data
    },

    statusisboolFun() {
      this.lodingIsbool = false
    },
    onSubmit() {
      console.log('submit!')
    },
    handleClose() {
      this.dialogVisibleopen = false
    },
    eitdClick(item) {
      console.log(item)
      this.dialogVisibleopen = true
    },
    handleRowDoubleClick(row, column, event) {
      // 处理双击事件
      console.log('双击了行', row)
      getDataextractionJobDetail(row.id).then((response) => {
        if (response.data.code === 0) {
          this.$message.success('获取详细信息成功')
          this.lodingIsbool = true
          this.details = response.data.data
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    handleDoneSingle(info) {
      this.openSingle = false
    },
    runJobNow(row) {
      startOneForSpark({ id: row.id }).then((res) => {
        if (res.data.code == 0) {
          this.$message.success(res.data.msg)
          this.getList()
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    getList() {
      this.listLoading = true
      getDataextractionJobList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.openSingle = false
        this.setSort()
        this.listLoading = false
      })
    },
    handleCreate() {
      if (this.listQuery.directoryId) {
        this.$refs.form.handleCreate(this.listQuery.directoryId)
      } else {
        this.$message.warning('请选择目录')
      }
    },
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row.id)
    },
    handleStopOrOpen(row, type) {
      if (type === 'open') {
        var data = {
          id: row.id,
          scheduleType: row.scheduleType,
          checkStatus: '1',
        }
        this.StopOrOpen(data)
      } else {
        var data = {
          id: row.id,
          scheduleType: row.scheduleType,
          checkStatus: '2',
        }
        this.$confirm('确定停止该任务吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.StopOrOpen(data)
        })
      }
    },
    StopOrOpen(data) {
      stopDataextractionJob(data).then((response) => {
        if (response.data.code === 0) {
          this.getList()
          this.$message.success(response.data.msg)
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },

    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delDataextractionJob(row.id).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSync(row) {
      syncsource(row.id).then((res) => {
        if (res.data.code === 0) {
          this.getList()
          this.$message.success(response.data.msg)
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletesource(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.downloadLoading = true
      exportsource(this.ids).then((response) => {
        this.downloadLoading = true
        if (response.data.code === 0) {
          import('@/vendor/Export2Excel').then((excel) => {
            excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
            this.downloadLoading = false
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    handleChangeJobStatus(row, cmd, cmdLabel) {
      this.$confirm('你确定要' + cmdLabel + '该计划任务么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let obj = {
          jobName: row.jobName,
          id: row.id,
          checkStatus: cmd,
        }
        changeJobStatus(obj).then((response) => {
          const data = response.data
          if (data.code === 0) {
            this.$message.success(data.msg)
            this.getList()
          } else {
            this.$message.error(data.errmsg)
          }
        })
      })
    },
    setSort() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          // TODO：这里完成自己的业务处理
        },
      })
    },
    handleFilter() {
      if (this.listQuery.directoryId) {
        this.listQuery.page = 1
        this.getList()
      } else {
        this.$message.warning('请选择目录')
      }
    },

    //重置
    handleRest() {
      this.listQuery.directoryId = this.listQuery.directoryId
      if (this.listQuery.directoryId) {
        this.listQuery.page = 1
        this.listQuery.checkStatus = undefined
        this.listQuery.jobName = undefined
        this.getList()
      }
    },

    handleInput(_node, _data) {
      // 修改节点
      console.log(_node, _data)

      // 退出编辑状态
      if (_node.isEdit) {
        this.$set(_node, 'isEdit', false)
      }
    },

    handleSingle() {
      this.openSingle = true

      this.dialogStatus = 'create'

      this.editdata = { addroedit: 'create' }

      // this.$refs.single.open()
    },
    handleRoweditClick(row) {
      this.openSingle = true

      this.dialogStatus = 'update'

      this.editdata = { id: row.id, addroedit: 'update' }
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep(::-webkit-scrollbar) {
  display: block !important;
}

.table-expand {
  font-size: 0;
}

.table-expand label {
  width: 90px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}

.el-row {
  display: flex;
}

.el-col-5 {
  flex: 1;
}
</style>
